package com.example.newapplication.Fragment;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Rect;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.NotificationCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.example.newapplication.Bean.HeadDate;
import com.example.newapplication.Bean.InnerHeadData;
import com.example.newapplication.EquipmentManage.ShunhuaiEquipment;
import com.example.newapplication.EquipmentManage.WeixiuEquipment;
import com.example.newapplication.EquipmentManage.WejieEquipment;
import com.example.newapplication.EquipmentManage.YijieEquipment;
import com.example.newapplication.FinalSearch;
import com.example.newapplication.Message;
import com.example.newapplication.NetRequest;
import com.example.newapplication.View.AnimationNestedScrollView;
import com.example.newapplication.R;
import com.google.gson.Gson;
import com.veken.chartview.bean.ChartBean;
import com.veken.chartview.bean.PieChartBean;
import com.veken.chartview.drawtype.DrawBgType;
import com.veken.chartview.drawtype.DrawConnectLineType;
import com.veken.chartview.drawtype.DrawLineType;
import com.veken.chartview.view.BarChartView;
import com.veken.chartview.view.LineChartView;
import com.veken.chartview.view.PieChartView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class HeadFragment extends Fragment {

    ImageView message,search,yijie, weijie, weixiu, shunhuai ;
    TextView text1, text2, text3, text4, text5, text6, name ,shift;
    private AnimationNestedScrollView sv_view;
    private ArrayList<ChartBean> lineChartBeanList, barChartBeanList;
    private List<PieChartBean> mList;
    private int count = 1;
    private int busy,free;
    LineChartView lineChartView;
    BarChartView barChartView;
    PieChartView pieChartView;
    RecyclerView abnormalRe;
    private List<InnerHeadData> innerHeadDataList = new ArrayList<>();
    private ConstraintLayout TopBack,beizhu,abnormalText1,abnormalText2;
    public static int[] mipmap = new int[10];


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_head, container, false);
        return view;
    }



    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        init();
        drawLine();
        message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), Message.class);
                startActivity(intent);
            }
        });
        search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), FinalSearch.class);
                startActivity(intent);
            }
        });
        shift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                count += 1;
                if(count ==1){
                    if(lineChartBeanList != null)
                        lineChartBeanList.clear();
                    barChartView.setVisibility(View.GONE);
                    pieChartView.setVisibility(View.GONE);
                    beizhu.setVisibility(View.GONE);
                    drawLine();
                }else if(count==2){
                    if(barChartBeanList!=null)
                        barChartBeanList.clear();
                    lineChartView.setVisibility(View.GONE);
                    pieChartView.setVisibility(View.GONE);
                    beizhu.setVisibility(View.GONE);
                    drawBar();
                }else{
                    if(mList != null)
                        mList.clear();
                    lineChartView.setVisibility(View.GONE);
                    barChartView.setVisibility(View.GONE);
                    drawPie();
                    beizhu.setVisibility(View.VISIBLE);
                    count = 0 ;
                }
            }
        });
        yijie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), YijieEquipment.class);
                startActivity(intent);
            }
        });
        weijie.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WejieEquipment.class);
                startActivity(intent);
            }
        });
        weixiu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), WeixiuEquipment.class);
                startActivity(intent);
            }
        });
        //创建Notification，传入Context和channelId
        final Notification notification = new NotificationCompat.Builder(getActivity(), "chat")
                .setAutoCancel(true)
                .setContentTitle("收到聊天消息")
                .setContentText("今天晚上吃什么")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                //在build()方法之前还可以添加其他方法
                .build();
        shunhuai.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                Intent intent = new Intent(getActivity(), ShunhuaiEquipment.class);
//                startActivity(intent);
                //1、NotificationManager
                NotificationManager manager = (NotificationManager)getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
                /** 2、Builder->Notification
                 *  必要属性有三项
                 *  小图标，通过 setSmallIcon() 方法设置
                 *  标题，通过 setContentTitle() 方法设置
                 *  内容，通过 setContentText() 方法设置*/
                Notification.Builder builder = new Notification.Builder(getActivity());
                builder.setContentInfo("Content info")
                        .setContentText("设备在一楼会客大厅13号出口被异常带出")//设置通知内容
                        .setContentTitle("异常警告")//设置通知标题
                        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                        .setSmallIcon(R.mipmap.jinggao)//不能缺少的一个属性
                        .setSubText("Subtext")
                        .setTicker("滚动消息......")
                        .setWhen(System.currentTimeMillis());//设置通知时间，默认为系统发出通知的时间，通常不用设置

                if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                    NotificationChannel channel = new NotificationChannel("1001","my_channel",NotificationManager.IMPORTANCE_DEFAULT);
                    channel.enableLights(true); //是否在桌面icon右上角展示小红点
                    channel.setLightColor(Color.GREEN); //小红点颜色
                    channel.setShowBadge(true); //是否在久按桌面图标时显示此渠道的通知
                    manager.createNotificationChannel(channel);
                    builder.setChannelId("001");
                }

                Notification n = builder.build();
                //3、manager.notify()
                manager.notify(1001,n);
            }
        });

        sv_view.setOnAnimationScrollListener(new AnimationNestedScrollView.OnAnimationScrollChangeListener() {
            @Override
            public void onScrollChanged(float dy) {
                float searchLayoutNewTopMargin1 = dp2px(getActivity(), 180f) - dy;
//                float searchLayoutNewTopMargin2 = dp2px(getActivity(), 180f) - 2.0f*dy;
                //设备管家标题栏的消隐
                ConstraintLayout.LayoutParams params1 = (ConstraintLayout.LayoutParams) TopBack.getLayoutParams();
                params1.height = (int) searchLayoutNewTopMargin1;
               if (params1.height < dp2px(getActivity(), 65f)) {
                   params1.height = dp2px(getActivity(), 65f);
                   name.setVisibility(View.VISIBLE);
                }
                TopBack.setLayoutParams(params1);
                if (params1.height > dp2px(getActivity(), 65f)) {
                    name.setVisibility(View.GONE);
                }
                //异常设备标题栏的消隐
//                if(dy > dp2px(getActivity(), 295f)){
//                    abnormalText1.setVisibility(View.GONE);
//                    abnormalText2.setVisibility(View.VISIBLE);
//                    sv_view.setFocusableInTouchMode(false);
//                    sv_view.setFocusable(false);
//                }else{
//                    abnormalText1.setVisibility(View.VISIBLE);
//                    abnormalText2.setVisibility(View.GONE);
//                }
                if(abnormalText1 != null) {
                    if(dy >= dp2px(getActivity(), 295f)) {
                        abnormalText2.setVisibility(View.VISIBLE);
                    } else {
                        abnormalText2.setVisibility(View.GONE);
                    }
                }
//                ViewGroup.MarginLayoutParams params2= (ViewGroup.MarginLayoutParams) sv_view.getLayoutParams();
 //               params2.topMargin = (int) (searchLayoutNewTopMargin2);
 //               sv_view.setLayoutParams(params2);
                //设置透明度
                float text1NewTopMargin =  (dp2px(getActivity(), 150f) - dy);
                float textAlpha = 255 * text1NewTopMargin / dp2px(getActivity(), 150f);

                if (textAlpha < 0) {
                    textAlpha = 0;
                }
                //设置相关控件的LayoutParams  此处使用的是MarginLayoutParams，便于设置params的topMargin属性
                text1.setTextColor(text1.getTextColors().withAlpha((int) textAlpha));
                text2.setTextColor(text2.getTextColors().withAlpha((int) textAlpha));
                text3.setTextColor(text3.getTextColors().withAlpha((int) textAlpha));
                text4.setTextColor(text4.getTextColors().withAlpha((int) textAlpha));
                text5.setTextColor(text5.getTextColors().withAlpha((int) textAlpha));
                text6.setTextColor(text6.getTextColors().withAlpha((int) textAlpha));
            }
         });
        //构造数据
        if(!innerHeadDataList.isEmpty()) innerHeadDataList.clear();
        InnerHeadData innerHeadData1 = new InnerHeadData();
        innerHeadData1.machineName = "Apple iPhone 12 Pro";
        innerHeadData1.machineType = "移动设备";
        innerHeadData1.machineCode = "YD_2021_6819";
        innerHeadData1.userName = "Otis设备管家";
        innerHeadData1.userId = "10000001";
        innerHeadData1.borrowStatus = "GPS信号异常关闭";
        innerHeadData1.other= "1楼会客大厅3号出口";
        innerHeadDataList.add(innerHeadData1);
        innerHeadData1=null;
        InnerHeadData innerHeadData2 = new InnerHeadData();
        innerHeadData2.machineName = "Mi 10 Pro";
        innerHeadData2.machineType = "移动设备";
        innerHeadData2.machineCode = "YD_2021_6819";
        innerHeadData2.userName = "唐三皮";
        innerHeadData2.userId = "201801020217";
        innerHeadData2.borrowStatus = "GPS信号异常关闭";
        innerHeadData2.other= "1楼会客大厅3号出口";
        innerHeadDataList.add(innerHeadData2);
        innerHeadData2=null;
        InnerHeadData innerHeadData3 = new InnerHeadData();
        innerHeadData3.machineName = "RAZER 狼蛛";
        innerHeadData3.machineType = "移动设备";
        innerHeadData3.machineCode = "YD_2021_6820";
        innerHeadData3.userName = "许一坚";
        innerHeadData3.userId = "201801020224";
        innerHeadData3.borrowStatus = "设备已归还，但无法找到设备";
        innerHeadData3.other= "移动设备5号仓库";
        innerHeadDataList.add(innerHeadData3);
        innerHeadData3=null;
        InnerHeadData innerHeadData4 = new InnerHeadData();
        innerHeadData4.machineName = "RAZER 雷蛇 标准";
        innerHeadData4.machineType = "移动设备";
        innerHeadData4.machineCode = "YD_2021_6821";
        innerHeadData4.userName = "周小吕";
        innerHeadData4.userId = "201801020243";
        innerHeadData4.borrowStatus = "设备不再规定区域";
        innerHeadData4.other= "软件开发部3号工作组";
        innerHeadDataList.add(innerHeadData4);
        innerHeadData4=null;
        InnerHeadData innerHeadData5 = new InnerHeadData();
        innerHeadData5.machineName = "HP 暗影精灵6 Pro";
        innerHeadData5.machineType = "移动设备";
        innerHeadData5.machineCode = "YD_2021_7819";
        innerHeadData5.userName = "姚小金";
        innerHeadData5.userId = "201801020115";
        innerHeadData5.borrowStatus = "GPS信号异常关闭";
        innerHeadData5.other= "2楼产品部";
        innerHeadDataList.add(innerHeadData5);
        innerHeadData5=null;
        InnerHeadData innerHeadData6 = new InnerHeadData();
        innerHeadData6.machineName = "艾瑞尔 高清显示器";
        innerHeadData6.machineType = "移动设备";
        innerHeadData6.machineCode = "YD_2021_6919";
        innerHeadData6.userName = "一娜";
        innerHeadData6.userId = "201801020217";
        innerHeadData6.borrowStatus = "设备已归还，但无法找到设备";
        innerHeadData6.other= "移动设备2号仓库";
        innerHeadDataList.add(innerHeadData6);
        innerHeadData6=null;


        mipmap[0] = R.mipmap.tuijian1;
        mipmap[1] = R.mipmap.tuijian2;
        mipmap[2] = R.mipmap.tuijian3;
        mipmap[3] = R.mipmap.tuijian4;
        mipmap[4] = R.mipmap.tuijian5;
        mipmap[5] = R.mipmap.tuijian6;
        mipmap[6] = R.mipmap.tuijian7;
        mipmap[7] = R.mipmap.tuijian8;

        abnormalRe.addItemDecoration(new SpacesItemDecoration(10));
        abnormalRe.setAdapter(new AbnormalAdapter());
        abnormalRe.setLayoutManager(new LinearLayoutManager(getActivity()));
        abnormalRe.setFocusableInTouchMode(false);//scrollView 嵌套 RecyclerView 显示时会滚动到RecyclerView第一项,让recyclerView去除焦点



    }



    /**
     * 设置item的边距
     */
    public static class SpacesItemDecoration extends RecyclerView.ItemDecoration{
        private int space;

        public SpacesItemDecoration(int space) {
            this.space = space;
        }

        @Override
        public void getItemOffsets(Rect outRect, View view,
                                   RecyclerView parent, RecyclerView.State state) {
            outRect.bottom = space;
        }

    }

    public class AbnormalAdapter extends RecyclerView.Adapter<AbnormalHolder>{
        @NonNull
        @Override
        public AbnormalHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_abnormal,parent,false);
            AbnormalHolder abnormalHolder = new AbnormalHolder(view);
            return abnormalHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull AbnormalHolder holder, int position) {
            holder.img.setImageResource(mipmap[position]);
            holder.equipmentName.setText(innerHeadDataList.get(position).machineName);
            holder.equipmentType.setText(innerHeadDataList.get(position).machineType);
            holder.equipmentNum.setText(innerHeadDataList.get(position).machineCode);
            holder.userName.setText(innerHeadDataList.get(position).userName);
            holder.userNum.setText(innerHeadDataList.get(position).userId);
            holder.abnormalReason.setText(innerHeadDataList.get(position).borrowStatus);
            holder.abnormalAddress.setText(innerHeadDataList.get(position).other);
        }

        @Override
        public int getItemCount() {
            return innerHeadDataList.size();
        }
    }
    public class AbnormalHolder extends RecyclerView.ViewHolder{

        TextView equipmentName,equipmentType,equipmentNum,userName,userNum,abnormalReason,abnormalAddress;
        ImageView img;
        public AbnormalHolder(@NonNull View itemView) {
            super(itemView);
            img = itemView.findViewById(R.id.imageView3);
            equipmentName = itemView.findViewById(R.id.textView45);
            equipmentType = itemView.findViewById(R.id.textView47);
            equipmentNum = itemView.findViewById(R.id.textView52);
            userName = itemView.findViewById(R.id.textView46);
            userNum = itemView.findViewById(R.id.textView57);
            abnormalReason = itemView.findViewById(R.id.textView58);
            abnormalAddress = itemView.findViewById(R.id.textView56);
        }
    }



    private void init() {
        //消息和搜索
        message = getActivity().findViewById(R.id.message);
        search = getActivity().findViewById(R.id.imageView7);
        //设备管理
        yijie = getActivity().findViewById(R.id.textView7);
        weijie = getActivity().findViewById(R.id.textView6);
        weixiu = getActivity().findViewById(R.id.textView8);
        shunhuai = getActivity().findViewById(R.id.textView9);
        sv_view = getActivity().findViewById(R.id.search_sv_view);
        TopBack = getActivity().findViewById(R.id.constraintLayout3);
        //设备台数
        text1 = getActivity().findViewById(R.id.textView2);
        text2 = getActivity().findViewById(R.id.textView);
        text3 = getActivity().findViewById(R.id.textView17);
        text4 = getActivity().findViewById(R.id.textView15);
        text5 = getActivity().findViewById(R.id.textView13);
        text6 = getActivity().findViewById(R.id.textView14);
        name = getActivity().findViewById(R.id.name);
        shift = getActivity().findViewById(R.id.shift);
        beizhu = getActivity().findViewById(R.id.beizhu);
        //折线图等
        lineChartView = getActivity().findViewById(R.id.chart_view);
        barChartView = getActivity().findViewById(R.id.bar_chart_view);
        pieChartView = getActivity().findViewById(R.id.piechart_view);
        //异常设备列表
        abnormalRe = getActivity().findViewById(R.id.abnormal);
        abnormalText1 = getActivity().findViewById(R.id.textView11);
        abnormalText2 = getActivity().findViewById(R.id.textView59);

    }

    public static int dp2px(Context context, float dpValue) {
        if (null == context) {
            return 0;
        }
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    private void drawLine() {

        lineChartView.setyLableText("折线图");
        //设置点击背景（可以为图片，也可以为一个颜色背景，大小根据textAndClickBgMargin设置）
        lineChartView.setDrawBgType(DrawBgType.DrawBitmap);
        //设置图片资源
        lineChartView.setShowPicResource(R.mipmap.click_icon);
        //连接线为虚线（也可以为实现）
        lineChartView.setDrawConnectLineType(DrawConnectLineType.DrawDottedLine);
        lineChartView.setClickable(true);
        //是否需要画连接线
        lineChartView.setNeedDrawConnectYDataLine(true);
        //连接线的颜色
        lineChartView.setConnectLineColor(getResources().getColor(R.color.default_color));
        //是否需要背景
        lineChartView.setNeedBg(true);
        //lineChartView.setyLableText("设备最大借用次数");
        //画曲线图（也可以为折线图）
        lineChartView.setDrawLineType(DrawLineType.Draw_Curve);

        if (lineChartBeanList == null) {
            lineChartBeanList = new ArrayList<>();
        }
        if(lineChartBeanList != null) {
            lineChartBeanList.clear();
        }
        //添加数据
        lineChartView.setDefaultTextSize(24);
        Random random = new Random();
        for (int i = 1; i < 8; i++) {
            ChartBean lineChartBean = new ChartBean();
            lineChartBean.setValue(String.valueOf(random.nextInt(1000)));
            lineChartBean.setDate(String.valueOf(i));
            lineChartBeanList.add(lineChartBean);
        }
        lineChartView.setData(lineChartBeanList);
        lineChartView.setVisibility(View.VISIBLE);
    }

    private void drawBar() {

        //是否需要柱状图的背景
        barChartView.setNeedBg(true);
        //Y轴文字
        barChartView.setyLableText("柱状图");
        //是否需要连接线
        barChartView.setNeedDrawConnectYDataLine(true);
        //是否需要画Y轴刻度
        barChartView.setNeedDrawYScale(true);
        //连接线的样式为虚线（也可以为直线）
        barChartView.setDrawConnectLineType(DrawConnectLineType.DrawDottedLine);
        if (barChartBeanList == null) {
            barChartBeanList = new ArrayList<>();
        }
        Random random = new Random();
        for (int i = 0; i < 7; i++) {
            ChartBean bean = new ChartBean();
            bean.setDate(i + "");
            bean.setValue(100 * random.nextInt(10) + "");
            barChartBeanList.add(bean);
        }
        barChartView.setData(barChartBeanList);
        barChartView.setVisibility(View.VISIBLE);
    }
    private void drawPie() {
        //内圆中间文字
        pieChartView.setInsideText("Hello");
        //是否需要加载动画
        pieChartView.setIsNeedAnimation(true,5000);
        //是否需要背景
        pieChartView.setNeedInside(true);
        if(mList==null){
            mList = new ArrayList<>();
        }
//各个扇形的背景颜色
        int[] colors = new int[]{getResources().getColor(R.color.colorAccent),
                getResources().getColor(R.color.default_color),
                getResources().getColor(R.color.colorPrimary),
                getResources().getColor(R.color.endColor)};
        Random random = new Random();
        for(int i = 0;i<4;i++){
            PieChartBean pieChartBean = new PieChartBean();
            pieChartBean.setValue(random.nextInt(10)+i);
            pieChartBean.setColor(colors[i]);
            mList.add(pieChartBean);
        }
        pieChartView.setData(mList);
        pieChartView.setVisibility(View.VISIBLE);
    }
}